package cn.gx.kevin.common.thread;

import cn.gx.kevin.common.utils.SysConfigParams;
import org.slf4j.Logger;


import java.util.concurrent.*;

/**
 * 用于执行队列任务
 */
public class ExecuteThreadTask {

    final static Logger logger =  org.slf4j.LoggerFactory.getLogger(ExecuteThreadTask.class);

    private static ThreadPoolExecutor executor;

    static {
        int num = Integer.valueOf(   SysConfigParams.getConfig("taskThreadNum"));
        executor =  new ThreadPoolExecutor(2, num, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(30),
                new ThreadFactory() {
                    public Thread newThread(Runnable r) {
                        Thread th = new Thread(r,"basic-task-"+r.hashCode());
                        return th;
                    }
                }, new ThreadPoolExecutor.CallerRunsPolicy()) {
                    protected void beforeExecute(Thread t,Runnable r) {
                    }
                    protected void afterExecute(Runnable r,Throwable t) {
                    }
                    protected void terminated() {
                    }
                };

    }

    public static void exeTask(BaseTask task){
        try{
            executor.execute(task);
        }catch (Throwable x){
            logger.error("",x);
        }
    }

    public static void shutdown(){
        try{
            logger.info("shutdown ExecuteThreadTask Pool........");
            executor.shutdown();
        }catch (Throwable ex){
            logger.error("",ex);
        }
    }

}
